package com.nb.protocol.handle;

import com.nb.protocol.protocol.MessageHolder;
import com.nb.protocol.protocol.ProtocolHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * 解码Handler.
 *
 *
 * @author Yohann.
 */
public class ProtocolDecoder extends ByteToMessageDecoder {
    private static final Logger logger = Logger.getLogger(ProtocolDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < ProtocolHeader.HEADER_LENGTH) {
            // 数据包长度小于协议头长度
            logger.info("数据包长度小于协议头长度");
            return;
        }
        in.markReaderIndex();
        byte[] remoteAddr = new byte[6];
        in.readBytes(remoteAddr);

        byte[] cpuidBytes = new byte[12];
        in.readBytes(cpuidBytes);
        /*StringBuilder stringBuilder = new StringBuilder(40);
        for(byte b:cpuidBytes){
            stringBuilder.append(Integer.toHexString(b));
        }*/
        String cpuId = byteArray2HexString(cpuidBytes).toUpperCase();

        byte serial = in.readByte();
        short frame = in.readShort();
        byte type = in.readByte();

        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);

        MessageHolder messageHolder = new MessageHolder();
        messageHolder.setCpuIdBytes(cpuidBytes);
        messageHolder.setRemoteAddr(remoteAddr);
        messageHolder.setCpuId(cpuId);
        messageHolder.setSerial(serial);
        messageHolder.setFrame(frame);
        messageHolder.setType(type);
        messageHolder.setBody(bytes);
        //messageHolder.setSender(msg.sender());
        out.add(messageHolder);
    }

    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    public static String byteArray2HexString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        //先把byte[] 转换维char[]，再把char[]转换为字符串
        char[] chars = new char[bytes.length * 2]; // 每个byte对应两个字符
        final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        for (int i = 0, j = 0; i < bytes.length; i++) {
            chars[j++] = hexDigits[bytes[i] >> 4 & 0x0f]; // 先存byte的高4位
            chars[j++] = hexDigits[bytes[i] & 0x0f]; // 再存byte的低4位
        }

        return new String(chars);
    }
}
